<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="800px"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      @close="handleClose()"
      @open="handleOpen()"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        :disabled="!canEdit"
        v-loading="loading"
      >
        <el-form-item label="元指标编码" prop="indexCode">
          <el-input
            type="text"
            v-model="form.indexCode"
            :disabled="!!row"
            placeholder="请输入元指标编码"
          ></el-input>
        </el-form-item>
        <el-form-item label="元指标名称" prop="indexName">
          <el-input
            type="text"
            v-model="form.indexName"
            placeholder="组织+时间+业务名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="指标粒度" prop="indexGranularity">
          <el-select
            v-model="form.indexGranularity"
            placeholder="请选择指标粒度"
            size="small"
            :disabled="!!row"
          >
            <el-option
              v-for="item in dict.indexGranularity"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指标类型" prop="indexType">
          <el-select
            v-model="form.indexType"
            placeholder="请选择指标类型"
            size="small"
            :disabled="!!row"
            @change="handleIndexTypeChange"
          >
            <el-option
              v-for="item in dict.indexType"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 如果选择的指标类型是设备参数类，该字段不显示 -->
        <el-form-item
          v-if="form.indexType != 'ED'"
          label="指标一级分类"
          prop="indexSubTypeOne"
        >
          <el-select
            v-model="form.indexSubTypeOne"
            placeholder="请选择指标一级分类"
            size="small"
            :disabled="!!row"
            @change="handleIndexSubTypeOneChange"
          >
            <el-option
              v-for="item in dict.indexSubTypeOne_PD"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 如果选择的指标一级分类非能耗，该字段不显示(即能耗显示) -->
        <el-form-item
          v-if="form.indexSubTypeOne == 'ECM'"
          label="指标二级分类"
          prop="indexSubTypeTwo"
        >
          <el-select
            v-model="form.indexSubTypeTwo"
            placeholder="请选择指标二级分类"
            size="small"
            :disabled="!!row"
          >
            <el-option
              v-for="item in dict.indexSubTypeTwo_ECM"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 如果选择的指标类型为设备参数类，或选择的指标一级分类为设备故障，该字段必填，否则非必填 -->
        <el-form-item
          label="设备分类"
          prop="equipSortCode"
          :rules="[
            {
              required: form.indexType == 'ED' || form.indexSubTypeOne == 'EPF',
              message: '请选择设备分类',
              trigger: 'change',
            },
          ]"
        >
          <el-select
            v-model="form.equipSortCode"
            placeholder="请选择设备分类"
            size="small"
            filterable
            :disabled="!!row"
          >
            <el-option
              v-for="item in dict.equipSortcode"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指标单位" prop="indexUnit">
          <el-select
            v-model="form.indexUnit"
            placeholder="请选择指标单位"
            size="small"
            :disabled="!!row"
          >
            <el-option
              v-for="item in indexUnitOption"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品控关注" prop="qulityControl">
          <el-select
            v-model="form.qulityControl"
            placeholder="请选择品控关注"
            size="small"
          >
            <el-option
              v-for="item in dict.sys_yes_no"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联元指标" prop="defRelaDtosName">
          <el-input
            type="text"
            v-model="form.defRelaDtosName"
            readonly
            placeholder="请选择关联元指标"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleOpenIndexList"
            ></el-button>
          </el-input>
        </el-form-item>
        <!-- 如果选择的指标类型为设备参数类，不展示 -->
        <el-form-item
          v-if="form.indexType != 'ED'"
          label="组织维度"
          prop="bizOrgDimension"
          class="full-width"
        >
          <el-radio-group
            v-model="form.bizOrgDimension"
            size="small"
            :disabled="!!row"
          >
            <el-radio
              v-for="item in dict.indexBizOrgDimension"
              :key="item.codevalue"
              :label="item.codevalue"
              border
              >{{ item.codename }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 如果选择的指标类型为设备参数类，不展示 -->
        <el-form-item
          v-if="form.indexType != 'ED'"
          label="时间维度"
          prop="timeDimension"
          class="full-width"
        >
          <el-radio-group
            v-model="form.timeDimension"
            size="small"
            :disabled="!!row"
          >
            <el-radio
              v-for="item in dict.indexTimeDimension"
              :key="item.codevalue"
              :label="item.codevalue"
              border
              >{{ item.codename }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="form.indexType != 'ED'"
          label="数据分组维度"
          prop="dataGroupBy"
          class="full-width"
        >
          <el-radio-group
            v-model="form.dataGroupBy"
            size="small"
            :disabled="!!row"
          >
            <el-radio
              v-for="item in dict.indexDataGroupBy"
              :key="item.codevalue"
              :label="item.codevalue"
              border
              >{{ item.codename }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="元指标描述" prop="remark" class="full-width">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入元指标描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          v-if="canEdit"
          type="primary"
          :loading="saveloading"
          @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 指标列表 -->
    <MetaIndexList
      :visible.sync="indexListDialog.visible"
      :defaultValues="indexListDialog.defaultValues"
      :selectableCallBack="selectableCallBack"
      :multiple="true"
      @closeDialog="handleIndexListClose"
    ></MetaIndexList>
  </div>
</template>
<script>
import { saveIndex, getIndexDetail } from "@/api/indexMgmt/definition";
import { checkPermi } from "@/utils/permission";
import MetaIndexList from "@/views/components/metaIndexList";
export default {
  components: { MetaIndexList },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  dicts: [
    "sys_yes_no",
    "indexType",
    "indexBizOrgDimension",
    "indexTimeDimension",
    "indexGranularity",
    "indexSubTypeOne_PD",
    "indexSubTypeTwo_ECM",
    "equipSortcode",
    "indexUnit_ED",
    "indexUnit_PD",
    "indexDataGroupBy",
  ],
  data() {
    return {
      loading: false,
      form: {
        id: null,
        indexCode: null,
        indexName: null,
        indexGranularity: null,
        indexType: null,
        indexSubTypeOne: null,
        indexSubTypeTwo: null,
        equipSortCode: null,
        indexUnit: null,
        qulityControl: "N",
        defRelaDtos: [],
        defRelaDtosName: null,
        bizOrgDimension: null,
        timeDimension: null,
        dataGroupBy: null,
        remark: null,
      },
      rules: {
        indexCode: [
          { required: true, message: "请输入元指标编码", trigger: "change" },
          {
            pattern: /^YZB[0-9]{5,5}$/,
            message: "请输入YZB+五位序列号",
            trigger: "change",
          },
        ],
        indexName: [
          { required: true, message: "请输入元指标名称", trigger: "change" },
        ],
        indexGranularity: [
          { required: true, message: "请选择指标粒度", trigger: "change" },
        ],
        indexType: [
          { required: true, message: "请选择指标类型", trigger: "change" },
        ],
        indexSubTypeOne: [
          { required: true, message: "请选择指标一级分类", trigger: "change" },
        ],
        indexSubTypeTwo: [
          { required: true, message: "指标二级分类", trigger: "change" },
        ],
        // equipSortCode: [
        //   { required: true, message: "请选择设备分类", trigger: "change" },
        // ],
        indexUnit: [
          { required: true, message: "请选择指标单位", trigger: "change" },
        ],
        qulityControl: [
          { required: true, message: "请选择品控关注", trigger: "change" },
        ],
        bizOrgDimension: [
          { required: true, message: "请选择组织维度", trigger: "change" },
        ],
        timeDimension: [
          { required: true, message: "请选择时间维度", trigger: "change" },
        ],
        dataGroupBy: [
          { required: true, message: "请选择数据分组维度", trigger: "change" },
        ],
      },
      indexListDialog: {
        visible: false,
        defaultValues: [],
      },
      // 关联指标不允许选择自己
      selectableCallBack: (row) => {
        if (!this.row) {
          return true;
        }
        return row.id != this.row.id;
      },
      saveloading: false,
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    title() {
      if (this.disabled == true) {
        return "元指标详情";
      }
      if (!!this.row) {
        return "编辑元指标";
      }
      return "新增元指标";
    },
    canEdit() {
      // 优先组件参数控制
      if (this.disabled == true) {
        return false;
      }
      // 判断是否有编辑权限
      if (this.row?.id) {
        return checkPermi(["indexMgmt:definition:edit"]);
      }
      return true;
    },
    // 指标单位
    // 如果选择的指标类型为设备参数类，下拉选择范围为：indexUnit_ED
    // 如果选择的指标类型为生产绩效类，下拉选择范围为： indexUnit_PD
    indexUnitOption() {
      if (this.form.indexType == "ED") {
        return this.dict.indexUnit_ED;
      }
      return this.dict.indexUnit_PD;
    },
  },
  methods: {
    handleClose() {
      this.saveloading = false;
      this.resetFormData();
    },
    handleOpen() {
      this.getDetail();
    },
    getDetail() {
      if (!this.row?.id) {
        return;
      }
      this.loading = true;
      getIndexDetail(this.row.id)
        .then((res) => {
          if (res.code == 200 && res.data) {
            const {
              indexCode,
              indexName,
              indexGranularity,
              indexType,
              indexSubTypeOne,
              indexSubTypeTwo,
              equipSortCode,
              indexUnit,
              qulityControl,
              defRelaDtos,
              bizOrgDimension,
              timeDimension,
              dataGroupBy,
              remark,
            } = res.data;
            this.form = {
              indexCode,
              indexName,
              indexGranularity,
              indexType,
              indexSubTypeOne,
              indexSubTypeTwo,
              equipSortCode,
              indexUnit,
              qulityControl,
              defRelaDtos:
                defRelaDtos?.map((ele) => ({
                  indexId: ele.indexId,
                  relaIndexId: ele.relaIndexId,
                  indexName: ele.indexMetaDto?.indexName || "",
                })) || [],
              defRelaDtosName:
                defRelaDtos
                  ?.map((ele) => ele.indexMetaDto?.indexName || "")
                  .join(",") || "",
              bizOrgDimension,
              timeDimension,
              dataGroupBy,
              remark,
            };
          }
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    handleSubmit() {
      if (!this.canEdit) {
        return;
      }
      this.saveloading = true;
      this.$refs.ruleForm.validate((flag) => {
        if (flag) {
          const id = this.row?.id || null;
          const {
            indexCode,
            indexName,
            indexGranularity,
            indexType,
            indexSubTypeOne,
            indexSubTypeTwo,
            equipSortCode,
            indexUnit,
            qulityControl,
            defRelaDtos,
            bizOrgDimension,
            timeDimension,
            dataGroupBy,
            remark,
          } = this.form;

          const param = {
            id,
            indexCode,
            indexName,
            indexGranularity,
            indexType,
            indexSubTypeOne,
            indexSubTypeTwo,
            equipSortCode,
            indexUnit,
            qulityControl,
            defRelaDtos: defRelaDtos.map((ele) => ({
              indexId: ele.indexId,
              relaIndexId: ele.relaIndexId,
            })),
            bizOrgDimension,
            timeDimension,
            dataGroupBy,
            remark,
          };
          console.log(param);
          saveIndex(param)
            .then((res) => {
              if (res.code == 200) {
                this.msgSuccess(id ? "修改成功！" : "新增成功！");
                this.$emit("submit-success");
                this.dialogVisible = false;
              }
              this.saveloading = false;
            })
            .catch(() => {
              this.saveloading = false;
            });
        } else {
          this.saveloading = false;
        }
      });
    },
    resetFormData() {
      this.form = {
        id: null,
        indexCode: null,
        indexName: null,
        indexGranularity: null,
        indexType: null,
        indexSubTypeOne: null,
        indexSubTypeTwo: null,
        equipSortCode: null,
        indexUnit: null,
        qulityControl: "N",
        defRelaDtos: [],
        defRelaDtosName: null,
        bizOrgDimension: null,
        timeDimension: null,
        dataGroupBy: null,
        remark: null,
      };
      this.$refs.ruleForm?.resetFields();
    },
    handleOpenIndexList() {
      this.indexListDialog.defaultValues = this.form.defRelaDtos.map((ele) => ({
        id: ele.relaIndexId,
        indexName: ele.indexName,
      }));
      this.indexListDialog.visible = true;
    },
    handleIndexListClose(list) {
      this.form.defRelaDtos = list.map((ele) => ({
        indexId: this.row?.id || null,
        relaIndexId: ele.id,
        indexName: ele.indexName,
      }));
      this.form.defRelaDtosName = list.map((ele) => ele.indexName);
    },
    // 修改指标类型
    handleIndexTypeChange(value) {
      // 清空数据
      this.form.bizOrgDimension = "";
      this.form.timeDimension = "";
      this.form.dataGroupBy = "";
      this.form.indexSubTypeOne = "";
      this.form.indexSubTypeTwo = "";
    },
    // 修改指标一级分类
    handleIndexSubTypeOneChange(value) {
      // 清空数据
      if (value != "ECM") {
        this.form.indexSubTypeTwo = "";
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.el-form {
  display: flex;
  justify-content: space-between;
  flex-flow: wrap;
  .el-form-item {
    width: 49%;
    &.full-width {
      width: 100%;
    }
  }
  ::v-deep .el-form-item__content {
    display: flex;
    align-items: center;
    .system-num {
      white-space: nowrap;
      margin-left: 10px;
    }
    .el-date-editor.el-input,
    .el-select,
    .el-cascader,
    .factory-select {
      width: 100%;
    }
  }
}
</style>
